package com.charactor;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.Charset;

/**
 * @Description:
 * @Author: yangzhiwei
 * @Date: 2021/8/18 16:25
 */
public class GBKOrUTF8 {
    public static void main(String[] args) throws UnsupportedEncodingException {
        String str ="北京啊";// '北' 21271 '京' 20140


        for (int i = 0; i < str.length(); i ++) {

            char c = str.charAt(i);
            System.out.println(Integer.toBinaryString(c));
            //System.out.println(c);

        }
        System.out.println("");
        byte[] res = str.getBytes("unicode");
        for (int i = 0; i < res.length; i++) {
            System.out.print(byteToBit(res[i]));
        }
        System.out.println("  unicode");

        byte[] gbk = str.getBytes("gb2312");
        System.out.println("gbkl    " + gbk.length);
        for (int i = 0; i < gbk.length; i++) {
            System.out.print(byteToBit(gbk[i]));
        }
        System.out.println("  gbk");


        byte[] utf8 = str.getBytes("utf8");

        System.out.println("utf8" + utf8.length);

        for (int i = 0; i < utf8.length; i++) {
            System.out.print(byteToBit(utf8[i]));
        }
        System.out.println("  utf8");
        String bomTest = new String(utf8,"utf8");
        byte[] bomTestBytes = bomTest.getBytes();
        for (int i = 0; i < bomTestBytes.length; i++) {
            System.out.print(byteToBit(bomTestBytes[i]));
        }

        System.out.println("============test==============");
        System.out.println("unicode  " + str.getBytes("unicode").length);
        System.out.println("gb2312  " + str.getBytes("gb2312").length);
        System.out.println("utf8  " + str.getBytes("utf8").length);

        String encodeCityName = URLEncoder.encode("北京", "gb2312");
        String encodeProjectName = URLEncoder.encode("1", "gb2312");
        System.out.println(encodeCityName.length());
        System.out.println(encodeProjectName);
        System.out.println(Charset.defaultCharset().name());
        System.out.println(new String(str.getBytes(),"utf8"));


    }

    public static String byteToBit(byte b) {
        return ""
                + (byte) ((b >> 7) & 0x1) + (byte) ((b >> 6) & 0x1)
                + (byte) ((b >> 5) & 0x1) + (byte) ((b >> 4) & 0x1)
                + (byte) ((b >> 3) & 0x1) + (byte) ((b >> 2) & 0x1)
                + (byte) ((b >> 1) & 0x1) + (byte) ((b >> 0) & 0x1);
    }

    public static String charToBit(byte b) {
        return ""
                + (byte) ((b >> 7) & 0x1) + (byte) ((b >> 6) & 0x1)
                + (byte) ((b >> 5) & 0x1) + (byte) ((b >> 4) & 0x1)
                + (byte) ((b >> 3) & 0x1) + (byte) ((b >> 2) & 0x1)
                + (byte) ((b >> 1) & 0x1) + (byte) ((b >> 0) & 0x1);
    }
}
